/*
* 质量核验
* */

import 'dart:convert';

import 'package:center_beijing/api/material_science_api.dart';
import 'package:center_beijing/api/quality_api.dart';
import 'package:center_beijing/common/logutil.dart';
import 'package:center_beijing/common/notification.dart';
import 'package:center_beijing/common/styles.dart';
import 'package:center_beijing/common/utils.dart';
import 'package:center_beijing/config/global_config.dart';
import 'package:center_beijing/config/routeConfig.dart';
import 'package:center_beijing/widgets/custom_loading_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
class QualityVerification extends StatefulWidget {
  @override
  _QualityVerificationState createState() => _QualityVerificationState();
}

class _QualityVerificationState extends State<QualityVerification> with TickerProviderStateMixin {

  EasyRefreshController _controller = EasyRefreshController();
  CustomLoading loading = CustomLoading.withMessage('提交中...');
  List dataSource = [];
  int page = 1;
  int pageSize = 15;
  bool firstLoad = true;
  @override
  void initState() {
    super.initState();
    bus.on('refreshQualityList', (arg) {
      page = 1;
      // _controller.finishLoad(success: true, noMore: false);
      this.getAllQuality();
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    bus.off('refreshQualityList');
    super.dispose();
  }

  /*
  * 获取核验任务列表
  * */
  getAllQuality() async {
    var pass = {
      'queryFields': json.encode([
        {
          "columnName": 'projectSectionId',
          "dataType": "string",
          "operator": "=",
          "queryValue": GlobalConfig.selectFactory.tag
        }
      ]),
    'sortname':"t1.CHECK_DATE",
    'sortorder':"desc",
      'page': page,
      'limit': pageSize,
    };
    var result = await getQualityList(pass);
    if (this.page == 1) {
      dataSource.clear();
    }
    firstLoad = false;
    if (result != null && result['hasError'] == null) {
      this.setState(() {
        if (result['results'].length == 0) {
          _controller.finishLoad(success: true, noMore: true);
        } else {
          dataSource.addAll(result['results']);
          if (dataSource.length == result['totalRecordNum']) {
            _controller.finishLoad(success: true, noMore: true);
          }
        }
      });
    } else {
      _controller.finishLoad(success: true);
    }
  }

  /*
  * 删除领料单详情
  * */
  deleteMaterialDetail(value) async {
    loading.show(delay: 30);
    var result = await deleteElementSpotCheck({'id': value['id']});
    loading.dismiss();
    if (result != null&& result['hasError'] == null) {
      Fluttertoast.showToast(msg: '删除成功');
      page = 1;
      this.getAllQuality();
    }
    LogUtil.d(result);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('质量抽检'),
      ),
      body: Container(
        color: Styles.MainBackgroundColor,
        padding:
        EdgeInsets.fromLTRB(0, 0, 0, MediaQuery.of(context).padding.bottom+70),
        child: NotificationListener(
          onNotification: (_) {
            FocusScope.of(context).requestFocus(new FocusNode());
            return false;
          },
          child: EasyRefresh.custom(
              shrinkWrap: true,
              firstRefresh: true,
              controller: _controller,
              header: MaterialHeader(),
              footer: ClassicalFooter(
                  loadingText: '加载中',
                  loadText: '上拉加载',
                  noMoreText: '没有更多数据',
                  loadedText: '加载完成',
                  infoText: '更新于 %T',
                  textColor: Styles.NoMoreColor,
                  showInfo: false),
              onRefresh: () async {
                _controller.finishLoad(success: true, noMore: false);
                if (mounted) {
                  page = 1;
                  this.getAllQuality();
                }
              },
              emptyWidget: (dataSource.length == 0 && !firstLoad)
                  ? Center(
                child: Image(
                  image: AssetImage('assets/images/no_data.png'),
                  width: 128,
                  height: 150,
                ),
              )
                  : null,
              onLoad: () async {
                await Future.delayed(Duration(seconds: 2), () {
                  if (mounted) {
                    page++;
                    this.getAllQuality();
                  }
                });
              },
              slivers: <Widget>[
                SliverList(
                  delegate: SliverChildBuilderDelegate(
                        (context, index) {
                      return Column(
                        children: [
                          GestureDetector(
                            onTap: () {
                              if(this.dataSource[index]['checkStatus']!='1'){
                                Get.toNamed(RouteConfig.qualityForm,arguments: this.dataSource[index]);
                              }else{
                                Get.toNamed(RouteConfig.qualityFormDetail,arguments: this.dataSource[index]);
                              }
                            },
                            child: Container(
                              color: Colors.white,
                              margin: EdgeInsets.fromLTRB(
                                  0, Styles.spacing8, 0, 0),
                              padding: EdgeInsets.fromLTRB(
                                  Styles.spacing12,
                                  Styles.spacing8,
                                  Styles.spacing12,
                                  Styles.spacing8),
                              child: Row(
                                crossAxisAlignment:
                                CrossAxisAlignment.start,
                                children: [
                                  Expanded(
                                      child: Container(
                                        padding: EdgeInsets.fromLTRB(
                                            Styles.spacing12, 0, 0, 0),
                                        child: Column(
                                          crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                          children: [
                                            Row(
                                              crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                              children: [
                                                Container(
                                                  margin: EdgeInsets.only(right: Styles.spacing8),
                                                  width: 4.w,
                                                  height: 20.h,
                                                  color: Styles.BlueColor,
                                                ),
                                                Container(
                                                  child: Text(
                                                    "${this.dataSource[index]['checkNo']}",
                                                    style: TextStyle(
                                                        color: Styles
                                                            .DetailColor,
                                                        fontSize: Styles
                                                            .NormalFont),
                                                  ),
                                                ),
                                              ],
                                            ),
                                            Container(
                                              padding: EdgeInsets.fromLTRB(
                                                  0, Styles.spacing4, 0, 0),
                                              child: Text(
                                                '核验人：${this.dataSource[index]['checkUser']}',
                                                style: TextStyle(
                                                    color: Styles.DetailColor,
                                                    fontSize:
                                                    Styles.NormalFont),
                                              ),
                                            ),
                                            Container(
                                              padding: EdgeInsets.fromLTRB(
                                                  0, Styles.spacing4, 0, 0),
                                              child: Text(
                                                '核验时间：${this.dataSource[index]['checkDateStr']}',
                                                style: TextStyle(
                                                    color: Styles.DetailColor,
                                                    fontSize:
                                                    Styles.NormalFont),
                                              ),
                                            ),
                                          ],
                                        ),
                                      )),
                                  Container(
                                    child: Text("${this.dataSource[index]['checkStatus']=='1'?'已提交':'未提交'}",style: TextStyle(color: this.dataSource[index]['checkStatus']=='1'?Styles.BlueColor:Styles.RedColor,fontSize: Styles.NormalFont),),
                                  )
                                ],
                              ),
                            ),
                          ),
                          this.dataSource[index]['checkStatus']!='1'?GestureDetector(
                            onTap: () {
                              FocusScope.of(context).requestFocus(new FocusNode());
                              showDialog(
                                  barrierDismissible: false,
                                  context: this.context,
                                  builder:
                                      (BuildContext context) {
                                    return AlertDialog(
                                      title: Text('注意'),
                                      content: Text('确认删除吗？'),
                                      actions: <Widget>[
                                        new Container(
                                          child: FlatButton(
                                            child: new Text(
                                              "取消",
                                              style: TextStyle(
                                                  color: Colors
                                                      .black),
                                            ),
                                            onPressed: () {
                                              Navigator.pop(
                                                  context);
                                            },
                                          ),
                                        ),
                                        new Container(
                                          child: FlatButton(
                                            child: new Text(
                                              "确定",
                                              style: TextStyle(
                                                  color: Colors
                                                      .red),
                                            ),
                                            onPressed: () {
                                              Navigator.pop(
                                                  context);
                                              this.deleteMaterialDetail(
                                                  this.dataSource[index]);
                                            },
                                          ),
                                        ),
                                      ],
                                    );
                                  });

                            },
                            child: Container(
                              padding:
                              EdgeInsets.all(Styles.spacing16),
                              decoration: BoxDecoration(
                                  border: Border(top: BorderSide(color: Styles.LineColor,width: 1)),color: Colors.white),
                              alignment: Alignment.center,
                              child: Text(
                                '删除',
                                style: TextStyle(
                                    color: Styles.DetailColor,
                                    fontSize: Styles.NormalFont),
                              ),
                            ),
                          ):Container()
                        ],
                      );
                    },
                    childCount: dataSource.length,
                  ),
                ),
              ])
        ),
      ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        floatingActionButton: Container(
          padding: EdgeInsets.fromLTRB(
              Styles.spacing8, Styles.spacing8, Styles.spacing8, 10),
          child: Container(
            decoration: new BoxDecoration(
              //背景
              color: Styles.BlueColor,
              //设置四周圆角 角度
              borderRadius: BorderRadius.all(Radius.circular(12.0)),
            ),
            child: FlatButton(
              disabledColor: Styles.SelectColor,
              onPressed: () {
                FocusScope.of(context).requestFocus(new FocusNode());
                showDialog(
                    barrierDismissible: false,
                    context: this.context,
                    builder:
                        (BuildContext context) {
                      return AlertDialog(
                        title: Text('注意'),
                        content: Text('确认发起核验吗？'),
                        actions: <Widget>[
                          new Container(
                            child: FlatButton(
                              child: new Text(
                                "取消",
                                style: TextStyle(
                                    color: Colors
                                        .black),
                              ),
                              onPressed: () {
                                Navigator.pop(
                                    context);
                              },
                            ),
                          ),
                          new Container(
                            child: FlatButton(
                              child: new Text(
                                "确定",
                                style: TextStyle(
                                    color: Colors
                                        .red),
                              ),
                              onPressed: () {
                                Navigator.pop(
                                    context);
                                Get.toNamed(RouteConfig.qualityForm);
                              },
                            ),
                          ),
                        ],
                      );
                    });

              },
              child: Container(
                height: Styles.MainButtonHeight,
                alignment: Alignment.center,
                child: Text(
                  '发起质量抽检',
                  style: TextStyle(
                      fontSize: Styles.MainButtonTextFont, color: Colors.white),
                ),
              ),
            ),
          ),
        )
    );
  }
}
